package com.zhanghp.class05.compare;

import com.zhanghp.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author zhanghp
 * @since 2023/11/18 15:25
 */
public class ShowComparator {

    // 小的id放前
    public static class IdCompare implements Comparator<Student>{
        // 如果返回负数，认为第一个参数应该排在前面
        // 如果返回正数，认为第二个参数应该排在前面
        // 如果返回0，认为谁放前面无所谓
        @Override
        public int compare(Student o1, Student o2) {
            if (o1.id > o2.id) {
                return 1;
            }else if(o1.id < o2.id){
                return -1;
            }else {
                return 0;
            }
        }
    }

    // 谁age大，谁放前！
    public static class AgeComparator implements Comparator<Student> {

        // 如果返回负数，认为第一个参数应该排在前面
        // 如果返回正数，认为第二个参数应该排在前面
        // 如果返回0，认为谁放前面无所谓
        @Override
        public int compare(Student o1, Student o2) {
            if (o1.age < o2.age) {
                return 1;
            } else if (o2.age < o1.age) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    public static void main(String[] args) {
        Student s1 = new Student("张三", 5, 27);
        Student s2 = new Student("李四", 1, 17);
        Student s3 = new Student("王五", 4, 29);
        Student s4 = new Student("赵六", 3, 9);
        Student s5 = new Student("左七", 2, 34);

        Student[] students = { s1, s2, s3, s4, s5 };
        Student.printStudent(students);
        CommonUtils.printDivingLine();
        Arrays.sort(students, new IdCompare());
        Student.printStudent(students);

        CommonUtils.printDivingLine();
        ArrayList<Student> arrList = new ArrayList<>();
        arrList.add(s1);
        arrList.add(s2);
        arrList.add(s3);
        arrList.add(s4);
        arrList.add(s5);
        Student.printStudent(arrList);
        arrList.sort(new IdCompare());
        CommonUtils.printDivingLine();
        Student.printStudent(arrList);

    }
}
